/*
 * Based on arch/arm/mm/ioremap.c
 *
 * (C) Copyright 1995 1996 Linus Torvalds
 * Hacked for ARM by Phil Blundell <philb@gnu.org>
 * Hacked to allow all architectures to build, and various cleanups
 * by Russell King
 * Copyright (C) 2012 ARM Ltd.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include <seminix/pgtable.h>
#include <seminix/slab.h>
#include <asm/io.h>
#include <asm/fixmap.h>

static u64 io_fixmap_current = __fix_to_virt(FIX_IOREMAP);
static u64 io_fixmap_end = __fix_to_virt(FIX_IOREMAP_END);

static phys_addr_t io_pte_alloc(int shift)
{
    unsigned long virt = __get_free_page(GFP_ZERO);

    BUG_ON(!virt);

    return (phys_addr_t)virt_to_phys((void *)virt);
}

void *__ioremap(phys_addr_t phys_addr, size_t size, pgprot_t prot)
{
    void *virt;
    size_t size_aligned = round_up(size, UTILS_PAGE_SIZE);

    if (!IS_ALIGNED(phys_addr, UTILS_PAGE_SIZE))
        return NULL;

    if (io_fixmap_current + size_aligned >= io_fixmap_end) {
        pr_warn("Ioremap is overflow range!\n");
        return NULL;
    }

    BUG_ON(io_fixmap_current % UTILS_PAGE_SIZE);

    virt = __fixmap_remap_phys(io_fixmap_current, phys_addr, size_aligned, prot, io_pte_alloc);
    if (virt)
        io_fixmap_current += size_aligned;

    return virt;
}
